package com.conversationboard.model;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.conversationboard.database.Database;
import com.conversationboard.database.Queries;

public class FileUpload {

	public static UploadedFile store(User user, String originalFileName, long size, String fileName, boolean isImage) throws SQLException {

		Connection connection = null;

		try {

			connection = Database.getConnection();

			PreparedStatement statement = connection.prepareStatement(Queries.INSERT_FILE);
			statement.setString(1, user.getLoginId());
			statement.setString(2, originalFileName);
			statement.setLong(3, size);
			statement.setString(4, fileName);
			statement.setBoolean(5, isImage);

			statement.executeUpdate();
			statement.close();

			UploadedFile file = new UploadedFile();
			file.setFileName(fileName);
			file.setOriginalFileName(originalFileName);
			file.setTimestamp(new Date());
			file.setImage(isImage);

			return file;

		} finally {
			Database.close(connection);
		}

	}


	/**
	 * Function to get a page of the users uploaded files.
	 * 
	 * @param user
	 * @param offset
	 * @param number
	 * @return
	 * @throws SQLException
	 */

	public static List<UploadedFile> getUploadedFiles(User user, int offset, int number) throws SQLException {

		Connection connection = null;
		List<UploadedFile> files = new ArrayList<UploadedFile>();

		try {

			connection = Database.getConnection();

			PreparedStatement statement = connection.prepareStatement(Queries.GET_MY_FILE_UPLOADS);
			statement.setString(1, user.getLoginId());
			statement.setInt(2, offset);
			statement.setInt(3, number);

			statement.execute();

			ResultSet resultSet = statement.getResultSet();

			while (resultSet.next()) {

				UploadedFile file = new UploadedFile();
				file.setTimestamp(resultSet.getTimestamp("timestamp"));
				file.setOriginalFileName(resultSet.getString("originalfilename"));
				file.setSize(resultSet.getLong("size"));
				file.setFileName(resultSet.getString("filename"));
				file.setImage(resultSet.getBoolean("image"));

				files.add(file);
			}

			statement.close();

			return files;

		} finally {
			Database.close(connection);
		}

	}

}
